package com.ruoyi.framework.interceptor;

import com.ruoyi.common.annotation.CheckMiniUser;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author bing.li
 * @date 2021/8/21  15:12
 */
@Component
@Slf4j
public class MiniInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            //取出token
            String auth = request.getHeader("auth");

            if(method.isAnnotationPresent(CheckMiniUser.class)){
                if(StringUtils.isBlank(auth)){
                    throw new LoginException("请求"+method.getName()+"未携带登录信息");
                }
                final String minUser = request.getParameter("minUser");
                if(StringUtils.isBlank(minUser)){
                    throw new LoginException("账号异常，请重新登录");
                }
            }
            return true;
        }
        else
        {
            return super.preHandle(request, response, handler);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
